package demo1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPEchoClient {
    private DatagramSocket client;
    //服务端的ip和端口号
    private String IP;
    private int port;
    public UDPEchoClient(String IP, int port) throws SocketException {
        this.IP = IP;
        this.port = port;
        client=new DatagramSocket();
    }

    /**
     * 客户端开始工作
     */
    public void start() throws IOException {
        System.out.println("客户端开始工作      ");
        Scanner scanner=new Scanner(System.in);
        while (true){

            String requestString=scanner.nextLine();
            //向服务端发送一个请求
            DatagramPacket request=new DatagramPacket(
                    requestString.getBytes(StandardCharsets.UTF_8),
                    0,
                    requestString.getBytes().length,
                    new InetSocketAddress(this.IP,this.port)
            );
            client.send(request);
            //接受服务器的回应
            DatagramPacket response=new DatagramPacket(new byte[1024],1024);
            client.receive(response);
            //解析数据
            String responseString=new String(response.getData(),0, response.getLength(),"UTF-8");
            //打印日志
            System.out.println(requestString+" ->"+responseString);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient client=new UDPEchoClient("10.111.55.77",9999);
        client.start();
    }
}
